<?php

class Application_Model_News extends Zend_Db_Table_Abstract
{
    protected $_name = 'news';
    protected $_primary = 'news_id';
    
    //get all news
    public function Get_All_News(){
        try {
            $select = $this->select();
            return $select;
        }
        catch (Zend_Exception $ex){
            echo $ex;
        }
    }
    
    //get 10 newest of news
    public function Get_Newest_News(){
        try {
            $select = $this->select()
                        ->order("news_datecreate DESC")
                        ->limit(10);
        return $this->fetchAll($select);
        }
        catch (Zend_Exception $ex){
            echo 'Error: ' .$ex->getMessage();
        }
    }
    
    //get news by news_id
    public function Get_News_by_ID($news_id){
        try {
            $select = $this->select()
                            ->from($this->_name)
                            ->setIntegrityCheck(false)
                            ->where("news_id = ?", $news_id);
            return $this->fetchRow($select);
        }
        catch (Zend_Exception $ex){
            echo $ex->getMessage();
        }
    }
    
    //get the viewest of news
    public function Get_The_Viewest_of_News(){
        try {
            $select = $this->select()
                           ->setIntegrityCheck(false)
                           ->order("news_counter DESC")
                           ->limit(10);
            return $this->fetchAll($select);
        }
        catch (Zend_Exception $ex){
            echo 'Error: ' .$ex->getMessage();
        }
    }
    
    //count number of user view news
    public function Count_Number_of_News_Viewed($news_id){
        try {
            $select = $this->select()
                           ->from($this->_name)
                           ->where("news_id = ?", $news_id);
            $row = $this->fetchRow($select);
            if(!empty($row)){
                $count = $row->news_counter;
                $count += 1;
                $data = array(
                        "news_counter"=>$count,
                );
                $where = 'news_id = ' .$news_id;
                $this->update($data, $where);
                return $count;
            }
            
        }
        catch (Zend_Exception $ex){
            echo 'Error: ' .$ex->getMessage();
        }
    }

}

